<?php defined('SYSPATH') or die('No direct script access.');
/**
 * $Id: topic.php 50 2008-07-27 09:06:29Z geertdd $
 *
 * @package    PianissiBoard
 * @author     Geert De Deckere
 */
class Topic_Model extends Model {

	/**
	 * Gets list of (all) topics.
	 *
	 * @param   array  query settings (id, limit, offset)
	 * @return  array|FALSE
	 */
	public function get($config = array())
	{
		// Build query, oh yeah!
		$sql = 'SELECT t.id, t.title, t.slug, t.sticky, t.closed,
				  COUNT(1) AS post_count,
				  p.id AS last_post_id,
				  p.author AS last_post_author,
				  UNIX_TIMESTAMP(p.date) AS last_post_date
				FROM '.Kohana::config('pianissiboard.table_prefix').'topics t
				  LEFT JOIN (SELECT id, topic_id, author, date FROM '.Kohana::config('pianissiboard.table_prefix').'posts ORDER BY date DESC) p
				  ON t.id = p.topic_id ';

		// One specific topic id
		if (isset($config['id']))
		{
			if ((int) $config['id'] < 1)
				return FALSE;

			$sql.= 'WHERE t.id = '.(int) $config['id'].' ';
		}

		// Continue building query
		$sql.= 'GROUP BY t.id
				ORDER BY t.sticky ASC, p.date DESC ';

		// Add LIMIT
		if (isset($config['limit']))
		{
			$sql.= 'LIMIT '.(int) $config['limit'].' ';

			// Add OFFSET
			if (isset($config['offset']))
			{
				$sql.= 'OFFSET '.(int) $config['offset'];
			}
		}

		return $this->db->query($sql);
	}

	/**
	 * Gets a single topic.
	 *
	 * @param   integer  topic id
	 * @return  array|FALSE
	 */
	public function get_by_id($topic_id)
	{
		if (($result = $this->get(array('id' => $topic_id))) === FALSE)
			return FALSE;

		return $result->current();
	}

	/**
	 * Count (all) topics.
	 *
	 * @param   array    query settings
	 * @return  integer
	 */
	public function count($config = array())
	{
		return (int) $this->db->query('SELECT COUNT(1) AS count FROM '.Kohana::config('pianissiboard.table_prefix').'topics')->current()->count;
	}

	/**
	 * Create a new topic.
	 *
	 * @param   array    topic data with keys matching fields
	 * @return  integer  insert id
	 */
	public function add($topic)
	{
		return $this->db->query
		(
			'INSERT INTO '.Kohana::config('pianissiboard.table_prefix').'topics (title, slug) VALUES (?, ?)',
			$topic['title'], $topic['slug']
		)
		->insert_id();
	}

	public function edit() {}
	public function delete() {}

}